<?php

/**
 * 用户登录
 *
 * @author haifeng.wu
 */

class Application_Model_UserLogin extends Application_Model_User
{
    /**
     * Cookie生存时间
     * @var int
     */
    protected $_timeToLive = 3600;

    /**
     * 登录的记录集
     * @var array
     */
    protected $_loginedRow;

    /**
     * 用户当前角色记录集
     * @var array
     */
    protected $_roleRow;

    /**
     * 实例
     * @var Application_Model_UserLogin
     */
    protected static $_instance;

    /**
     * 构造函数
     * 
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取实例
     * 
     * @return void
     */
    public static function getInstance()
    {
        if (self::$_instance == NULL) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 登录(返回状态，0：成功，10：用户名或者密码错误，20：用户被锁)
     * 
     * @param string $userName
     * @param string $password
     * @return int
     */
    public function login($userName, $password)
    {
        $row = $this->fetchRow("`userName` = '". addslashes($userName) ."' ");
        $rowCount = empty($row) ? 1 : 2;
        if ($rowCount == 1) {
            $status = 10;
        } else if ($password == '') {
            $status = 10;
        } else if (md5($password) != $row['password']) {
            $status = 10;
        } else if ($row['status'] == 2) {
            $status = 20;
        } else {
            //加入会话
            $time = time();
            $cookieModel = new Application_Model_Cookie();
            $userSessionModel = new Application_Model_UserSession();
            $userSessionField = array();
            $userSessionField['userName'] = $userName;
            $userSessionField['time'] = date("Y-m-d H:i:s", $time);
            $userSessionField['ip'] = getClientIP();
            $userSessionField['lastOnlineTime'] = date("Y-m-d H:i:s", $time);
            $sessionId = $userSessionModel->insert($userSessionField);

            //更新当前sessionId
            $this->update(array('sessionId'=>$sessionId), "`userId` = '". addslashes($row['userId']) ."'");

            //设置cookie
			$cookieModel->setCookie('userId', $row['userId'], $time + $this->_timeToLive);
            $cookieModel->setCookie('adminUserName', $row['userName'], $time + $this->_timeToLive);
            $cookieModel->setCookie('adminUserPassword', $password, $time + $this->_timeToLive);
            $cookieModel->setCookie('adminUserSessionId', $sessionId, $time + $this->_timeToLive);
            $cookieModel->setCookie('adminUserIp', $userSessionField['ip'], $time + $this->_timeToLive);
            //更新状态
            $status = 0;
        }
        return $status;
    }

    /**
     * 退出
     * 
     * @return void
     */
    public static function logout()
    {
        $cookieModel = new Application_Model_Cookie();
        $userName = $cookieModel->getCookie('adminUserName');
        $password = $cookieModel->getCookie('adminUserPassword');
        $sessionId = $cookieModel->getCookie('adminUserSessionId');
		$userId = $cookieModel->getCookie('userId');
        if ($cookieModel->getCookie('adminUserName')) {
            $cookieModel->setCookie('adminUserName', NULL, 0);
        }
        if ($cookieModel->getCookie('adminUserPassword')) {
            $cookieModel->setCookie('adminUserPassword', NULL, 0);
        }
        if ($cookieModel->getCookie('adminUserSessionId')) {
            $cookieModel->setCookie('adminUserSessionId', NULL, 0);
        }
		if ($cookieModel->getCookie('userId')) {
            $cookieModel->setCookie('userId', NULL, 0);
        }
    }

    /**
     * 登录验证(返回状态，0：成功，10：用户名或者密码错误，20：用户被锁，30：会话错误)
     * 
     * @param 1/2 $update 1更新cookie和在线时间，2只更新在线时间，其他不更新
     * @return int
     */
    public function loginCheck($update = 1)
    {
        $cookieModel = new Application_Model_Cookie();
		$userId = $cookieModel->getCookie('userId');
        $userName = $cookieModel->getCookie('adminUserName');
        $password = $cookieModel->getCookie('adminUserPassword');
        $sessionId = $cookieModel->getCookie('adminUserSessionId');
        if (trim($userName) == '' || trim($password) == '' || trim($sessionId) == '' || trim($userId) == '') {
            $status = 10;
        } else {
            if (!empty($this->_loginedRow)) {
                $row = $this->_loginedRow;
            } else {
                $row = $this->fetchRow("`userId` = '". addslashes($userId) ."'");
            }
            if (empty($row)) {
                $status = 10;
            } else if (md5($password) != $row['password']) {
                $status = 10;
            } else if ($row['status'] == 2) {
                $status = 20;
            } else if ($row['sessionId'] != $sessionId) {
                $status = 30;
            } else {
                $this->_loginedRow = $row;
                $time = time();
                if ($update == 1 || $update == 2) {
                    $userSessionModel = new Application_Model_UserSession();

                    //更新最后在线时间
                    $userSessionModel->update(array('lastOnlineTime'=>date("Y-m-d H:i:s", $time)), "`userName` = '". addslashes($userName) ."' AND `id` = {$sessionId}");
                }
                if ($update == 1) {
                    //设置cookie
					$cookieModel->setCookie('userId', $row['userId'], $time + $this->_timeToLive);
                    $cookieModel->setCookie('adminUserName', $userName, $time + $this->_timeToLive);
                    $cookieModel->setCookie('adminUserPassword', $password, $time + $this->_timeToLive);
                    $cookieModel->setCookie('adminUserSessionId', $sessionId, $time + $this->_timeToLive);
                }
                //更新状态
                $status = 0;
            }
        }
        return $status;
    }

    /**
     * 获取登录用户所有角色对应的资源列表
     * 
     * @return array
     */
    public function getAllRoleResource()
    {
        $resourceModel = new Application_Model_Resource();
        $roleResourceModel = new Application_Model_RoleResource();
        $allRoleTmp = $this->getUserCurrentAllRole();
        $allRole = array();
        foreach ($allRoleTmp as $item) {
            $allRole[] = $item['roleId'];
        }
        $sql = "SELECT b.resourceId,b.module,b.controller,b.action,a.roleId FROM `{$roleResourceModel->getTableName()}` AS a 
                INNER JOIN `{$resourceModel->getTableName()}` AS b 
                ON a.resourceId = b.resourceId 
                WHERE a.roleId in ('".implode("','", $allRole)."')";
        $allAccessResource = $resourceModel->getAdapter()->fetchAll($sql);
        return $allAccessResource;
    }


    /**
     * 获取登录用户的所有的角色
     * 
     * @return array
     */
    public function getUserCurrentAllRole()
    {
        $userRoleModel = new Application_Model_UserRole();
        $roleModel = new Application_Model_Role();
        $myRoleRows = $roleModel->getAdapter()->fetchAll("
            SELECT `r`.* FROM `{$roleModel->getTableName()}` AS `r` 
            INNER JOIN `{$userRoleModel->getTableName()}` AS `ur` ON `r`.`roleId` = `ur`.`roleId`
            WHERE `ur`.`userId` = {$this->_loginedRow['userId']}
            ORDER BY `r`.`roleId` DESC
        ");
        return $myRoleRows;
    }

    /**
     * 检查用户是否拥有此角色权限
     * 
     * @param string $roleId
     * @return 1/0
     */
    public function userIsHaveRole($roleId)
    {
        $isHave = NULL;
        $userRoleModel = new Application_Model_UserRole();
        $myRoleNumRow = $userRoleModel->getAdapter()->fetchRow("
            SELECT COUNT(*) AS `c` FROM `{$userRoleModel->getTableName()}` 
            WHERE `userId` = {$this->_loginedRow['id']} AND `roleId` = {$roleId}
        ");
        $isHave = $myRoleNumRow['c'] > 0 ? 1 : 0;
        return $isHave;
    }

    /**
     * 检查用户是否登录
     * 
     * @return boolean
     */
    public static function isLogined()
    {
        $cookieModel = new Application_Model_Cookie();

        if ($cookieModel->getCookie('adminUserName') && $cookieModel->getCookie('adminUserPassword') && $cookieModel->getCookie('adminUserSessionId') && $cookieModel->getCookie('userId')) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取登录的用户Row
     * 
     * @return int
     */
    public function getLoginedRow()
    {
        if (empty($this->_loginedRow)) {
            $this->loginCheck(false);
        }
        return $this->_loginedRow;
    }

    /**
     * 设置登录信息的生存时间
     * 
     * @param int $time
     * @return void
     */
    public function setTimeToLive($time)
    {
        $this->_timeToLive = $time;
    }

    /**
     * 获取登录信息的生存时间
     * 
     * @return int
     */
    public function getTimeToLive()
    {
        return $this->_timeToLive;
    }

}